package com.baozhun.mall.common.util.onkeylogin

import android.app.Activity
import android.app.ProgressDialog
import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.BuildConfig
import com.baozhun.mall.common.R
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.mAppViewModel
import com.baozhun.mall.common.network.mCommonApiService
import com.baozhun.mall.common.util.config.SDKConfig
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.PreLoginResultListener
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.TokenRet
import com.orhanobut.logger.Logger
import me.hgj.jetpackmvvm.ext.request

/**
 * @Title：一键登录帮助类
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2023/10/18
 * @Version：1.0.0
 */
class OneKeyLoginByAliHelper {

    private lateinit var mPhoneNumberAuthHelper: PhoneNumberAuthHelper
    private var mTokenResultListener: TokenResultListener? = null
    private var mUIConfig: BaseUIConfig? = null
    private var mSdkAvailable = true
    private var mProgressDialog: ProgressDialog? = null
    private var mToken: String? = null
    private var mContext: Activity? = null

    companion object {
        const val CUSTOM_VIEW = 5
        const val TIME_OUT = 5000
        const val NEED_INTERCEPTOR = "needInterceptor"
        fun getInstance() = InstanceHelper.sSingle
    }

    object InstanceHelper {
        val sSingle = OneKeyLoginByAliHelper()
    }

    /**
     * 初始化一键登录sdk
     */
    fun initOneKeyLogin(context: Activity) {
        mContext = context
        var checkListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                try {
                    Logger.e("checkEnvAvailable：$s")
                    val pTokenRet: TokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS == pTokenRet.code) {
                        accelerateLoginPage(TIME_OUT)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                mSdkAvailable = false
                Logger.e("checkEnvAvailable：$s")
                //终端环境检查失败之后 跳转到其他号码校验方式
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(context, checkListener)
        mPhoneNumberAuthHelper.reporter.setLoggerEnable(BuildConfig.DEBUG)
        mPhoneNumberAuthHelper.setAuthSDKInfo(SDKConfig.ONE_KEY_LOGIN_SECRET)
        mPhoneNumberAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
    }

    /**
     * 在不是一进app就需要登录的场景 建议调用此接口 加速拉起一键登录页面
     * 等到用户点击登录的时候 授权页可以秒拉
     * 预取号的成功与否不影响一键登录功能，所以不需要等待预取号的返回。
     * @param timeout
     */
    fun accelerateLoginPage(timeout: Int) {
        mPhoneNumberAuthHelper.accelerateLoginPage(timeout, object : PreLoginResultListener {
            override fun onTokenSuccess(s: String) {
                Logger.e("预取号成功: $s")
            }

            override fun onTokenFailed(s: String, s1: String) {
                Logger.e("预取号失败: $s1")
            }
        })
    }
    /**
     * 拉起授权页
     */
    fun startLoginAuthPage() {
        mUIConfig = BaseUIConfig.init(CUSTOM_VIEW, ActivityUtils.getTopActivity(), mPhoneNumberAuthHelper)
        mUIConfig?.configAuthPage()
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                hideLoadingDialog()
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        Logger.e("唤起授权页成功：$s")
                    }
                    if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                        Logger.e("获取token成功：$s")
                        mToken = tokenRet.token
                        loginByOneKeyLogin(mToken)
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                Logger.e("获取token失败：$s")
                hideLoadingDialog()
                mPhoneNumberAuthHelper.hideLoginLoading()
                //如果环境检查失败 使用其他登录方式
                var tokenRet: TokenRet? = null
                try {
                    ToastUtils.showShort(com.baozhun.mall.res.R.string.one_key_login_failure_hint)
                    ARouter.getInstance().build(RoutePath.Me.LOGIN).withBoolean(NEED_INTERCEPTOR, false)
                        .navigation()
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                mPhoneNumberAuthHelper.quitLoginPage()
                mPhoneNumberAuthHelper.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper.setAuthListener(mTokenResultListener)
        mPhoneNumberAuthHelper.getLoginToken(mContext, TIME_OUT)
        showLoadingDialog("正在唤起授权页")
    }

    private fun showLoadingDialog(hint: String?) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(mContext)
            mProgressDialog?.setProgressStyle(ProgressDialog.STYLE_SPINNER)
        }
        mProgressDialog?.setMessage(hint)
        mProgressDialog?.setCancelable(true)
        mProgressDialog?.show()
    }

    fun hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog?.dismiss()
        }
    }

    /**
     * 一键登录
     */
    fun loginByOneKeyLogin(token: String?) {
        mAppViewModel.request({ mCommonApiService.oneKeyLogin(token,"") }, {
            EventBusUtils.sendEvent(EventCode.LOGIN_SUCCESS)
            //登录成功
            mPhoneNumberAuthHelper.quitLoginPage()
            mPhoneNumberAuthHelper.setAuthListener(null)
        }, isShowDialog = true, showSuccessMsg = true)
    }

}